<template>
  <div :class="anchorLinkClasses">
    <a :class="linkTitleClasses" :href="href" :data-scroll-offset="getScrollOffset()" :data-href="href" @click.prevent="goAnchor" :title="title">{{ title }}</a>
    <slot></slot>
  </div>
</template>

<script setup>
import {inject,nextTick, computed,ref,onMounted,onBeforeUnmount, getCurrentInstance, onBeforeMount} from "vue"
import { useRouter,useRoute } from 'vue-router'
// import random_str from "../../utils/random_str";
import {isClient} from "../../utils/index"
defineOptions({
  name:'AnchorLink'
})

const AnchorInstance=inject('AnchorInstance');

const props=defineProps({
  href: String,
  title: String,
  scrollOffset: {
    type: Number,
    // default () {
    //   return AnchorInstance.scrollOffset;
    // }
  }
})
const router=useRouter()
const $route=useRoute()
const prefixCls=ref('haloe-anchor-link')
const instance=getCurrentInstance();
const id=ref(instance.uid);


const {currentLink,scrollOffset,handleHashChange,handleScrollTo,onSelect,addLink,init,removeLink}=AnchorInstance

// console.log('currentLink//',currentLink, AnchorInstance.currentLink===props.href,scrollOffset,handleHashChange)
const anchorLinkClasses=computed(()=>{
  return [
    prefixCls.value,
    // AnchorInstance.currentLink === props.href ? `${prefixCls.value}-active` : ''
    currentLink.value === props.href ? `${prefixCls.value}-active` : ''
  ]
})

const linkTitleClasses=computed(()=> {
  return [
    `${prefixCls.value}-title`
  ];
})

const getScrollOffset=()=>{
  if(!props.scrollOffset){
    // return AnchorInstance.scrollOffset
    return scrollOffset.value
  }else{
    return props.scrollOffset
  }
}

const goAnchor= ()=> {
  // AnchorInstance.handleHashChange();
  // AnchorInstance.handleScrollTo();
  handleHashChange();
  nextTick(()=>{
    handleScrollTo();
  })
  // handleScrollTo();
  // AnchorInstance.onSelect(props.href);
  onSelect(props.href);

  if (router) {
    router.push(props.href, () => {});
  } else {
    isClient && (window.location.href = props.href);
  }
}

onMounted(() => {
  // AnchorInstance.addLink(id.value, getCurrentInstance().proxy);
  addLink(id.value, instance.proxy);
  nextTick(()=>{
    // AnchorInstance.init();
    init();
  })
})

onBeforeUnmount(() => {
  // AnchorInstance.removeLink(id.value);
  removeLink(id.value);
})
</script>

<style>

</style>